﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Filters;

namespace Common
{
    public class ApiHandleErrorAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 重写异常处理方法 add by caoheyang 20150205   需要将该特性标注于各个controller上。
        /// </summary>
        /// <param name="filterContext">上下文对象  该类继承于ControllerContext</param>
        public override void OnException(HttpActionExecutedContext filterContext)
        {
            string errMsg = LogWriterFromFilter(filterContext.Exception);
            filterContext.Response = new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent("发生错误") };
        }

        /// <summary>
        /// 捕获全局异常
        /// </summary>
        /// <param name="error"></param>
        public string LogWriterFromFilter(Exception error)
        {
            try
            {
                StringBuilder logstr = new StringBuilder("\r\n-----------------start----------------------\r\n");
                //异常发生地址
                logstr.Append("异常发生地址:").Append(HttpContext.Current.Request.Url.AbsoluteUri.ToString()).Append("\r\n");
                logstr.Append("请求类型:").Append(HttpContext.Current.Request.RequestType.ToString()).Append("\r\n");
                logstr.Append("异常:").Append(error.ToString()).Append("\r\n");
                logstr.Append("--------------------end---------------------\r\n");
                return logstr.ToString();
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
